package com.fanketly.funacg2.ui.screen

import android.graphics.Bitmap
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.DismissValue
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.rememberSwipeableState
import androidx.compose.material.swipeable
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.graphics.drawable.toBitmap
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import androidx.palette.graphics.Palette
import coil.compose.AsyncImage
import com.fanketly.funacg2.App
import com.fanketly.funacg2.R
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.data.model.convertToWork
import com.fanketly.funacg2.data.paging.rememberLazyListState
import com.fanketly.funacg2.ui.components.FilterMenu
import com.fanketly.funacg2.ui.components.HomeListCard
import com.fanketly.funacg2.ui.components.MiGuAudioProgressBar
import com.fanketly.funacg2.ui.components.PlayListIconButton
import com.fanketly.funacg2.ui.components.PlayOrPauseIconButton
import com.fanketly.funacg2.ui.navigation.toShowThisTagScreen
import com.fanketly.funacg2.ui.screen.destinations.PlayListDestination
import com.fanketly.funacg2.ui.theme.FunACG2Theme
import com.fanketly.funacg2.ui.theme.dp8
import com.fanketly.funacg2.ui.viewmodels.HomeViewModel
import com.fanketly.funacg2.ui.viewmodels.MusicViewModel
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.launch

@RootNavGraph(true)
@Destination
@Composable
fun Home(
    homeViewModel: HomeViewModel,
    musicViewModel: MusicViewModel,
    navigator: DestinationsNavigator,
) {
//    val homeUiState: HomeState = homeViewModel.homeUiState
    var expanded by remember { mutableStateOf(false) }
    var selectedFilterData by homeViewModel.selectedFilterData
    val scope = rememberCoroutineScope()
    LaunchedEffect(key1 = Unit, block = {
        Log.i(TAG, "Home_LaunchedEffect:$selectedFilterData ")
        homeViewModel.selectOrder(selectedFilterData)
    })
    val lazyPagingItems = homeViewModel.pager.collectAsLazyPagingItems()
    val lazyListState = lazyPagingItems.rememberLazyListState()
//    val lazyListState = rememberLazyListState()
    Column(Modifier.fillMaxSize()) {
        Row(modifier = Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) {
            if (!App.sIsAllAges)
                FilterMenu(expanded = expanded,
                    selectedOptionText = selectedFilterData.name,
                    onDismissRequest = { expanded = false },
                    onExpandedChange = { expanded = expanded.not() },
                    onItemClick = {
                        scope.launch {
                            if (selectedFilterData.name != it.name) {
                                lazyListState.scrollToItem(0)
//                            delay(200L)
                                homeViewModel.selectOrder(it)
                                lazyPagingItems.refresh()
                                selectedFilterData = it
                                expanded = false
                            }
                        }
                    })
            Spacer(modifier = Modifier.weight(1f))
//            PlayingIconButton(
//                modifier = Modifier
//                    .size(24.dp),
//                isPlaying = musicViewModel.isPlaying
//            ) {//跳转到音频详情页
//                homeViewModel.getAudio(musicViewModel.audioInfo.convertToWork())
//            }
        }
        Box(Modifier.fillMaxSize()) {
            HomeCardList(lazyPagingItems, lazyListState, onTagClick = {
                navigator.toShowThisTagScreen(it, homeViewModel)
            }, homeViewModel::getAudio)
            BottomProgressBar(musicViewModel = musicViewModel, toDetail = {
                if (musicViewModel.audioInfo.songUrl.isNotEmpty()) homeViewModel.getAudio(
                    musicViewModel.audioInfo.convertToWork()
                )
            }) {
                navigator.navigate(PlayListDestination)
            }
        }
    }
//    when (homeUiState) {
//        HomeState.EMPTY -> Text("Empty")
//        HomeState.LoadFailed -> Text(
//            "Error",
//            modifier = Modifier.clickable(onClick = homeViewModel::reload)
//        )
//        HomeState.Loading -> Text("Loading")
//        is HomeState.Success -> HomeCardList2(homeViewModel.pager, homeViewModel::getAudio)
//        HomeState.NotAuthorization -> Text(
//            "NotAuthorization", modifier = Modifier.clickable(onClick = homeViewModel::reload)
//        )
//    }
//    HomeListContent(audioUiState, homeViewModel::reload, homeViewModel::getAudio)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeCardList(
    lazyPagingItems: LazyPagingItems<WorkList.Work>,
    lazyListState: LazyListState,
    onTagClick: (tag: Int) -> Unit,
    getAudio: (WorkList.Work) -> Unit,
) {
    if (lazyPagingItems.loadState.refresh == LoadState.Loading) {
        LinearProgressIndicator(
            modifier = Modifier.fillMaxWidth()
        )
    } else LazyColumn(
        modifier = Modifier
            .fillMaxSize(),
        state = lazyListState,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        items(
            lazyPagingItems.itemCount,
            key = lazyPagingItems.itemKey { it.id }
        ) { index ->
            val work = lazyPagingItems[index]
            if (work == null) {
                ElevatedCard(
                    onClick = {},
                    modifier = Modifier
                        .fillMaxWidth(0.9f)
                        .height(200.dp)
                        .padding(top = dp8, bottom = dp8),
                ) {}
            } else {
                HomeListCard(work, onTagClick) {
                    getAudio(work)
                }
            }
        }
        item { Spacer(modifier = Modifier.height(58.dp)) }
        if (lazyPagingItems.loadState.append == LoadState.Loading) {
            item {
                CircularProgressIndicator(
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentWidth(Alignment.CenterHorizontally)
                )
            }
        }
    }
}

@Composable
fun BoxScope.BottomProgressBar(
    musicViewModel: MusicViewModel,
    toDetail: () -> Unit,
    toPlayList: () -> Unit,
) {
    val colorPrimary = MaterialTheme.colorScheme.primary.toArgb()
    val primaryContainer = MaterialTheme.colorScheme.surface.toArgb()
    Log.i(TAG, "BottomProgressBar: ")
    BottomProgressBarContent(
        musicViewModel.audioInfo.songCover,
        musicViewModel.audioInfo.songName,
        musicViewModel.audioAllTime,
        musicViewModel.audioProcess,
        musicViewModel.isPlaying,
        colorPrimary,
        primaryContainer,
        modifier = Modifier.align(Alignment.BottomCenter),
        nextMusic = { musicViewModel.next() },
        previousMusic = {
            musicViewModel.previous()
        },
        onPlayOrPause = musicViewModel::pauseOrRestoreMusic,
        toDetail = toDetail,
        toPlayList = toPlayList
    )
}

/**
 * height:50dp
 * */
@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun BottomProgressBarContent(
    imgUrl: Any,
    title: String,
    allTime: Int,
    nowTime: Int,
    isPlaying: Boolean,
    colorPrimary: Int,
    primaryContainer: Int,
    modifier: Modifier = Modifier,
    nextMusic: () -> Unit,
    previousMusic: () -> Unit,
    onPlayOrPause: () -> Unit,
    toDetail: () -> Unit,
    toPlayList: () -> Unit,
) {
    var backgroundColor by remember {
        mutableIntStateOf(primaryContainer)
    }
    var barColor by remember {
        mutableIntStateOf(colorPrimary)
    }
    BoxWithConstraints(
        modifier = modifier
            .padding(bottom = 4.dp, start = 16.dp, end = 16.dp)
            .fillMaxWidth(), contentAlignment = Alignment.CenterStart
    ) {
        MiGuAudioProgressBar(
            if (allTime == 0) 0f else nowTime.toFloat() / allTime,
            shape = RoundedCornerShape(bottomEnd = 25.dp, topEnd = 25.dp),
            barColor = Color(barColor),
            barBackgroundColor = Color(backgroundColor)
        )
        Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
            AsyncImage(
                model = imgUrl,
                placeholder = painterResource(id = R.drawable.ic_cd),
                error = painterResource(id = R.drawable.ic_cd),
                onSuccess = {
                    val generate = Palette.from(
                        it.result.drawable.toBitmap().copy(Bitmap.Config.RGBA_F16, true)
                    ).generate()
                    val dominantColor = generate.getLightMutedColor(colorPrimary)
                    val mutedColor = generate.getMutedColor(barColor)
                    backgroundColor = dominantColor
                    barColor = mutedColor
                    Log.d(TAG, "BottomProgressBarContent: $mutedColor,$dominantColor")
                },
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .size(50.dp)
                    .clip(CircleShape)
                    .clickable(onClick = toDetail)
            )
            val state = rememberSwipeableState(
                initialValue = DismissValue.Default,
                confirmStateChange = {
                    if (it == DismissValue.DismissedToStart) {
                        previousMusic()
                    } else if (it == DismissValue.DismissedToEnd) {
                        nextMusic()
                    }
                    true
                })
            val anchors = mapOf(
                200f to DismissValue.DismissedToStart,
                -200f to DismissValue.DismissedToEnd,
                0f to DismissValue.Default
            )
            Text(
                text = title,
                color = Color.Black,
                modifier = Modifier
                    .weight(1f)
                    .padding(horizontal = 6.dp)
                    .swipeable(state, anchors, Orientation.Horizontal)
//                        .draggable(
//                            orientation = Orientation.Horizontal,
//                            state = rememberDraggableState(onDelta),
//                            onDragStarted = onDragStarted,
//                            onDragStopped = onDragStopped
//                        )
                ,
                style = MaterialTheme.typography.titleSmall,
                overflow = TextOverflow.Ellipsis,
                maxLines = 2
            )
            Row() {
                PlayOrPauseIconButton(
                    isPlaying = isPlaying,
                    tint = MaterialTheme.colorScheme.onPrimaryContainer,
                    onClick = onPlayOrPause
                )
                PlayListIconButton(
                    tint = MaterialTheme.colorScheme.onPrimaryContainer,
                    toPlayList = toPlayList
                )
            }
        }
    }
}
//@Composable
//fun HomeListContent(homeState: HomeState, reload: () -> Unit, getAudio: (WorkList.Work) -> Unit) {
//    when (homeState) {
//        HomeState.EMPTY -> Text("Empty")
//        HomeState.LoadFailed -> Text("Error", modifier = Modifier.clickable(onClick = reload))
//        HomeState.Loading -> Text("Loading")
//        is HomeState.Success -> HomeCardList(homeState.list, getAudio)
//        HomeState.NotAuthorization -> Text(
//            "NotAuthorization", modifier = Modifier.clickable(onClick = reload)
//        )
//    }
//
//}


//@Composable
//fun HomeCardList(workList: WorkList, getAudio: (WorkList.Work) -> Unit) {
//    LazyColumn(
//        modifier = Modifier.fillMaxWidth(),
//        horizontalAlignment = Alignment.CenterHorizontally,
//    ) {
//        items(workList.works, key = { it.id }) {
//            HomeListCard(it) {
//                getAudio(it)
//            }
//        }
//    }
//}

//@Preview(showBackground = true, uiMode = UI_MODE_NIGHT_YES)
@Preview(showBackground = true)
@Composable
private fun DefaultPreview() {
    FunACG2Theme {
        Box(Modifier.fillMaxSize()) {
            Column(
                Modifier
                    .fillMaxWidth()
                    .verticalScroll(rememberScrollState())
            ) {

                repeat(5) {
                    HomeListCard(WorkList.Work(
                        WorkList.Work.Circle(1, ""),
                        1,
                        "2023",
                        1,
                        true,
                        1,
                        "",
                        "1",
                        true,
                        1,
                        emptyList(),
                        1.0,
                        1,
                        emptyList(),
                        "2023",
                        1,
                        "",
                        tags = emptyList(),
                        "",
                        "1",
                        userRating = 4,
                        listOf(WorkList.Work.Va("1", "233"))
                    ), {}) {}
                }
                Spacer(modifier = Modifier.height(58.dp))
            }
            val colorPrimary = MaterialTheme.colorScheme.primary.toArgb()
            val primaryContainer = MaterialTheme.colorScheme.primaryContainer.toArgb()
            BottomProgressBarContent(
                R.drawable.ic_cd,
                "title1111111111111111111111111111111111",
                100,
                95,
                false,
                colorPrimary, primaryContainer,
                Modifier.align(Alignment.BottomCenter),
                {}, { }, {}, {}) {}
        }

    }
//        }
//    }
}

